// AppEvent_streambuf.h: interface for the AppEvent_streambuf class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_APPEVENT_STREAMBUF_H__0FEA40ED_7F1C_40B9_8BE0_C0EC12E53A02__INCLUDED_)
#define AFX_APPEVENT_STREAMBUF_H__0FEA40ED_7F1C_40B9_8BE0_C0EC12E53A02__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "AppEventRecord.h"
#include <streambuf>

/************************************************************************/
/*                                                                      */
/************************************************************************/
typedef std::basic_streambuf<char> std_streambuf;

class AppEvent_streambuf  : public std_streambuf
{
	typedef std_streambuf::int_type int_type;
public:
	AppEvent_streambuf()
	{
		m_pbuffer = new char[BUFFER_SIZE + 1];// the last one is reserved for '\0'
		m_pbuffer[BUFFER_SIZE] = '\0';
		setp(m_pbuffer,m_pbuffer + BUFFER_SIZE);
	}
	virtual	~AppEvent_streambuf()
	{
		delete m_pbuffer;
	}

	
public:	

protected:
	virtual int_type overflow(int_type c = std::char_traits<char>::eof())
	{
		sync();
		if(c != std::char_traits<char>::eof())
		{
			sputc(std::char_traits<char>::to_char_type(c));
		}
		return c;
	}

	virtual int sync()
	{
		int nSize = pptr() - m_pbuffer;//nSize must not greater than BUFFER_SIZE
		if(m_pbuffer[nSize - 1] != '\0')
			m_pbuffer[nSize] = '\0';//make sure the last byte is '\0'. It's string, isn't it?
		
		int nOffset = 0;
		int nLen = 0;
		for(;nOffset < nSize;)
		{
			flush_(m_pbuffer + nOffset);
			nOffset += strlen(m_pbuffer + nOffset) + 1;			
		}
		setp(m_pbuffer,m_pbuffer + BUFFER_SIZE);
		return 0;
	}

	void flush_(const char* pData)
	{		
		m_AppEventRecord.put(pData);
	}


protected:
	static const int BUFFER_SIZE;
	AppEventRecord m_AppEventRecord;

	char* m_pbuffer;


};

#endif // !defined(AFX_APPEVENT_STREAMBUF_H__0FEA40ED_7F1C_40B9_8BE0_C0EC12E53A02__INCLUDED_)
